<template>
  <div>
    <!-- 筛选区 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" class="filter-form" @submit.native.prevent>
        <el-row :gutter="16" style="width: 100%">
          <el-col :span="5">
            <el-form-item label="产品线(包含)">
              <el-input v-model="searchForm.productLine" placeholder="请输入产品线" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="订单编号(包含)">
              <el-input v-model="searchForm.orderCode" placeholder="请输入订单编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="BOM编号(包含)">
              <el-input v-model="searchForm.bomCode" placeholder="请输入BOM编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="物料批次(包含)">
              <el-input v-model="searchForm.materialBatch" placeholder="请输入物料批次" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4" class="filter-btns">
            <el-form-item>
              <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon> 查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-divider />

    <!-- 操作区 -->
    <div class="table-ops">
      <el-button
        type="danger"
        :disabled="!multipleSelection.length"
        @click="handleBatchDelete"
      >批量删除</el-button>
      <el-button type="success" @click="handleBatchImport">批量导入</el-button>
      <el-button type="primary" @click="openDialog()">新增</el-button>
    </div>

    <!-- 表格区 -->
    <el-card class="table-card">
      <el-table
        :data="pagedData"
        border
        style="width: 100%; margin-top: 0"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="processRoute" label="工艺线路" width="120" />
        <el-table-column prop="orderCode" label="订单编号" width="150" />
        <el-table-column prop="bomCode" label="BOM编号" width="120" />
        <el-table-column prop="materialCode" label="物料编码" width="150" />
        <el-table-column prop="materialBatch" label="物料批次" width="120" />
        <el-table-column prop="planQty" label="计划数量" width="100" />
        <el-table-column prop="actualQty" label="实际用量" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 16px;"
        background
        layout="prev, pager, next, jumper, ->, total, sizes"
        :total="filteredData.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="val => currentPage = val"
        @size-change="val => pageSize = val"
        :page-sizes="[10, 20, 50, 100]"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" class="dialog-form">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="工艺线路" prop="processRoute">
              <el-select v-model="form.processRoute" placeholder="请选择">
                <el-option v-for="item in processRouteOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderCode">
              <el-input v-model="form.orderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM编号" prop="bomCode">
              <el-select v-model="form.bomCode" placeholder="请选择">
                <el-option v-for="item in bomOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料批次" prop="materialBatch">
              <el-input v-model="form.materialBatch" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="该批次数量" prop="planQty">
              <el-input-number v-model="form.planQty" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="该批次实际用量" prop="actualQty">
              <el-input-number v-model="form.actualQty" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// mock数据
const processRouteOptions = ['磁阻传感器', '测速传感器']
const bomOptions = ['12321', '45678']

const mockData = [
  {
    id: 1,
    processRoute: '磁阻传感器',
    orderCode: 'DD2022070202',
    bomCode: '12321',
    materialCode: 'EXY101000036',
    materialBatch: '221001',
    planQty: 600,
    actualQty: 0,
    createdAt: '2022-11-04 22:32:00',
  },
  {
    id: 2,
    processRoute: '测速传感器',
    orderCode: '20231204',
    bomCode: '12321',
    materialCode: 'PCB101000037',
    materialBatch: '220610',
    planQty: 10,
    actualQty: 0,
    createdAt: '2023-12-04 16:00:00',
  },
]

const data = ref([...mockData])
const searchForm = reactive({
  productLine: '',
  orderCode: '',
  bomCode: '',
  materialBatch: '',
})
const multipleSelection = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

const filteredData = computed(() => {
  return data.value.filter(item => {
    return (
      (!searchForm.productLine || item.processRoute.includes(searchForm.productLine)) &&
      (!searchForm.orderCode || item.orderCode.includes(searchForm.orderCode)) &&
      (!searchForm.bomCode || item.bomCode.includes(searchForm.bomCode)) &&
      (!searchForm.materialBatch || item.materialBatch.includes(searchForm.materialBatch))
    )
  })
})
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredData.value.slice(start, start + pageSize.value)
})

function handleSearch() {
  currentPage.value = 1
}
function handleReset() {
  Object.keys(searchForm).forEach(k => (searchForm[k] = ''))
  currentPage.value = 1
}
function handleSelectionChange(val) {
  multipleSelection.value = val
}
function handleBatchDelete() {
  ElMessageBox.confirm('确定要批量删除选中的记录吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map(i => i.id)
      data.value = data.value.filter(item => !ids.includes(item.id))
      ElMessage.success('删除成功')
      multipleSelection.value = []
    })
}
function handleDelete(row) {
  ElMessageBox.confirm('确定要删除该条记录吗？', '提示', { type: 'warning' })
    .then(() => {
      data.value = data.value.filter(item => item.id !== row.id)
      ElMessage.success('删除成功')
    })
}
function handleBatchImport() {
  ElMessage.info('批量导入功能待实现')
}

// 弹窗表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = reactive({
  id: null,
  processRoute: '',
  orderCode: '',
  bomCode: '',
  materialCode: '',
  materialBatch: '',
  planQty: 1,
  actualQty: 0,
})
const formRef = ref()
const rules = {
  processRoute: [{ required: true, message: '请选择工艺线路', trigger: 'change' }],
  orderCode: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  bomCode: [{ required: true, message: '请选择BOM编号', trigger: 'change' }],
  materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  materialBatch: [{ required: true, message: '请输入物料批次', trigger: 'blur' }],
  planQty: [{ required: true, message: '请输入该批次数量', trigger: 'blur' }],
}
function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑'
    Object.assign(form, row)
  } else {
    dialogTitle.value = '新增'
    Object.assign(form, {
      id: null,
      processRoute: '',
      orderCode: '',
      bomCode: '',
      materialCode: '',
      materialBatch: '',
      planQty: 1,
      actualQty: 0,
    })
  }
  dialogVisible.value = true
}
function handleSubmit() {
  formRef.value.validate(valid => {
    if (!valid) return
    if (form.id) {
      // 编辑
      const idx = data.value.findIndex(i => i.id === form.id)
      if (idx > -1) {
        data.value[idx] = { ...form }
        ElMessage.success('编辑成功')
      }
    } else {
      // 新增
      form.id = Date.now()
      form.createdAt = new Date().toLocaleString()
      data.value.unshift({ ...form })
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
  })
}
</script>

<style scoped>
.filter-card {
  margin-bottom: 24px;
}
.filter-form {
  margin-bottom: 0;
}
.filter-btns {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  height: 56px;
}
.table-ops {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}
.table-card {
  margin-bottom: 24px;
}
.dialog-form .el-form-item {
  margin-bottom: 18px;
}
.required {
  color: #f56c6c;
  margin-right: 2px;
}
.dialog-form .el-form-item__label {
  font-weight: 500;
  color: #333;
}
.dialog-form .el-form-item__label::before {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
  margin-right: 2px;
}
</style>